/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var spiralOrder = function (matrix) {
  let x = y = 0;

  let ans = []

  let w = matrix[0].length
  let h = matrix.length

  let w_l = [0, matrix[0].length]
  let h_l = [0, matrix.length]

  while (w_l[1] - w_l[0] > 0 && h_l[1] - h_l[0] > 0) {

    if (h - (h_l[1] - 1 - h_l[0]) <= w - (w_l[1] - 1 - w_l[0])) {
      if (y == w_l[0]) {
        for (; y < w_l[1]; y++) {
          ans.push(matrix[x][y])
        }
        h_l[0]++
        y--
      } else {
        for (; y >= w_l[0]; y--) {
          ans.push(matrix[x][y])
        }
        h_l[1]--
        y++
      }
    } else {
      if (x == h_l[0]) {
        for (; x < h_l[1]; x++) {
          ans.push(matrix[x][y])
        }
        w_l[1]--
        x--
      } else {
        for (; x >= h_l[0]; x--) {
          ans.push(matrix[x][y])
        }
        x++
        w_l[0]++
      }
    }

  }

  console.log(ans)
};

spiralOrder([[1, 2, 3], [4, 5, 6], [7, 8, 9]])